package com.yuki.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.yuki.api.service.ITokenService;

import java.util.Date;

/**
 * @description:
 * @author: Yuki Tadayoshi
 * @time: 2021/3/25 15:53
 */
@Service(
        version = "1.0.0",
        interfaceName = "com.yuki.api.service.ITokenService",
        interfaceClass = ITokenService.class
)
public class TokenServiceImpl implements ITokenService {
    private static final long EXPIRE_TIME = 10 * 60 * 1000;

    @Override
    public String getToken(String userId, String password) {
        //JWT
        String token = "";
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create().withAudience(userId).withExpiresAt(date).sign(Algorithm.HMAC256(password));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    @Override
    public String getUserId(String token) {
        String userId = JWT.decode(token).getAudience().get(0);
        return userId;
    }

    @Override
    public boolean checkSign(String token, String password) {
        if (token == null) {
            throw new RuntimeException("无token,请重新登录");
        }
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(password)).build();
            verifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
